package com.nanjia.boot.invoicetypeconfig.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanjia.boot.invoicetypeconfig.converter.InvoiceTypeConverter;
import com.nanjia.boot.invoicetypeconfig.mapper.InvoiceTypeMapper;
import com.nanjia.boot.invoicetypeconfig.model.entity.InvoiceType;
import com.nanjia.boot.invoicetypeconfig.model.form.InvoiceTypeForm;
import com.nanjia.boot.invoicetypeconfig.model.query.InvoiceTypeQuery;
import com.nanjia.boot.invoicetypeconfig.model.vo.InvoiceTypeVO;
import com.nanjia.boot.invoicetypeconfig.service.InvoiceTypeService;
import com.nanjia.boot.common.enums.StatusEnum;
import com.nanjia.boot.core.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 发票类型服务实现类
 *
 * @author zhouyang
 * @since 2025-06-13 10:11
 */
@Service
@RequiredArgsConstructor
public class InvoiceTypeServiceImpl extends ServiceImpl<InvoiceTypeMapper, InvoiceType> implements InvoiceTypeService {

    private final InvoiceTypeConverter invoiceTypeConverter;

    private final InvoiceTypeMapper invoiceTypeMapper;

    /**
     * 获取发票类型分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<InvoiceTypeVO>} 发票类型分页列表
     */
    @Override
    public IPage<InvoiceTypeVO> getInvoiceTypePage(InvoiceTypeQuery queryParams) {
        Page<InvoiceTypeVO> pageVO = this.baseMapper.getInvoiceTypePage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取发票类型表单数据
     *
     * @param id 发票类型ID
     * @return 发票类型表单数据
     */
    @Override
    public InvoiceTypeForm getInvoiceTypeFormData(Long id) {
        InvoiceType entity = this.getById(id);
        return invoiceTypeConverter.toForm(entity);
    }

    /**
     * 新增发票类型
     *
     * @param formData 发票类型表单对象
     * @param ipAddr
     * @return 是否新增成功
     */
    @Override
    public boolean saveInvoiceType(InvoiceTypeForm formData, String ipAddr) {
        LambdaQueryWrapper<InvoiceType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(InvoiceType::getId);
        List<InvoiceType> list = this.list(queryWrapper);
        int x = 0;
        if (CollectionUtils.isNotEmpty(list)) {
            x = Integer.parseInt(list.get(0).getInvoiceTypeCode());
        }
        InvoiceType entity = invoiceTypeConverter.toEntity(formData);
        entity.setInvoiceTypeCode(String.format("%04d", x + 1));
        entity.setCreateBy(SecurityUtils.getUserStrId());
        entity.setCreateIp(ipAddr);
        return this.save(entity);
    }

    /**
     * 更新发票类型
     *
     * @param id       发票类型ID
     * @param formData 发票类型表单对象
     * @param ipAddr
     * @return 是否修改成功
     */
    @Override
    public boolean updateInvoiceType(Long id, InvoiceTypeForm formData, String ipAddr) {
        InvoiceType entity = invoiceTypeConverter.toEntity(formData);
        entity.setId(id);
        entity.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
        entity.setUpdateIp(ipAddr);
        entity.setUpdateTime(LocalDateTime.now());
        return this.updateById(entity);
    }

    /**
     * 删除发票类型
     *
     * @param ids    发票类型ID，多个以英文逗号(,)分割
     * @param ipAddr
     * @return 是否删除成功
     */
    @Override
    public boolean deleteInvoiceTypes(String ids, String ipAddr) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的发票类型数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();

        List<InvoiceType> list = new ArrayList<>();
        for (Long l : idList) {
            InvoiceType entity = new InvoiceType();
            entity.setId(l);
            entity.setInvoiceTypeStatus(StatusEnum.DELETE.getValue());
            entity.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
            entity.setUpdateTime(LocalDateTime.now());
            entity.setUpdateIp(ipAddr);
            list.add(entity);
        }
        return this.updateBatchById(list, list.size());
//        return this.removeByIds(idList);
    }

    @Override
    public List<InvoiceType> getInvoiceTypeList(Integer invoiceTypeStatus) {
        Map<String, Object> map = new HashMap<>();
        map.put("invoice_type_status", invoiceTypeStatus);
        List<InvoiceType> invoiceTypeList = invoiceTypeMapper.selectByMap(map);
        return invoiceTypeList;
    }
}
